<template>
     <!-- 面包屑导航区域-->
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图-->
  <el-card> 
      <!-- 添加角色区域-->
      <el-col>
          <el-button type="primary" @click="adddialogVisible=true">
              添加角色
          </el-button>
      </el-col>
      <!-- 角色列表区域-->
          <el-table :data="rolelist">
               <!-- 展开列-->
                     <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbotton', i1 === 0 ? '' : 'bdtop', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <!-- 通过for循环 渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6 ">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >{{ item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
              </el-table-column>
               <!-- 索引列-->
        <el-table-column type="index" border stripe ></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="角色操作" width="300px" >
            <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showeditroledialog(scope.row.id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removerolebyid(scope.row.id)">删除</el-button>
                <el-button size="mini" type="warning" icon="el-icon-setting"
                @click="showserrightdialog(scope.row)"
                >分配权限</el-button>
            </template>
        </el-table-column>
    </el-table>
  </el-card>
  <!-- 分配权限得对话框 -->
  <el-dialog
  title="分配权限"
  :visible.sync="setrightdialogVisible"
  width="50%"
  @click="setrightdialogclose">
  <!-- 树形空间 -->
 <el-tree :data="rightlist" :props="treeprops" show-checkbox
  @node-click="handleNodeClick" node-key="id" 
  default-expand-all :default-checked-keys="defkey" ref="treeref">
 </el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setrightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allrights">确 定</el-button>
  </span>
</el-dialog>
<!-- 添加角色的对话框 -->
<el-dialog
  title="添加角色"
  :visible.sync="adddialogVisible"
  width="60%"
  :before-close="handleClose">
   <!-- 内容主体 -->
    <span>
      <el-form :model="roleForm" ref="roleFormref" label-width="70px" class="demo-ruleForm" :rules="roleFormrules">
  <el-form-item label="角色名" prop="roleName">
    <el-input v-model="roleForm.roleName"></el-input>
  </el-form-item>
    <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="roleForm.roleDesc"></el-input>
    </el-form-item>
  </el-form>
  </span>
  <span slot="footer" class="dialog-footer"> 
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addrole">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改角色"
  :visible.sync="editroledialogVisible"
  width="50%"
  @close="editroledialogclose"
  >
   <!-- 内容主体区-->
  <span><el-form :model="editrolefrom" :rules="editroleFormrules"
   ref="editFormref" label-width="70px" >
  <el-form-item label="角色名" prop="roleName" >
    <el-input v-model="editrolefrom.roleName" ></el-input>
    </el-form-item>
    <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="editrolefrom.roleDesc"></el-input>
  </el-form-item>
  </el-form></span>

   <!-- 底部区域-->
  <span slot="footer" class="dialog-footer">
    <el-button @click="editroledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editroleinfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
    data() {
        return {
            // 所有角色得列表数据
            rolelist: {},
            // 控制分配权限对话框的显示和隐藏
            setrightdialogVisible:false,
            // 所有权限的合集
            rightlist:{},
            // 树形控件的绑定的那个对象
            treeprops: {
             label:'authName',
             children: 'children'
            },
            // 默认选中的节点id值数据
            defkey:[],
            // 监控添加角色对话框
            adddialogVisible:false,
            roleForm: {},
            roleFormrules: {
                roleName: [
                     { required: true, message: '请输入角色名', trigger: 'blur' },
                ],
                roleDesc: [
                     { required: true, message: '请输入角色描述', trigger: 'blur' },
                ]
            },
            editroledialogVisible:false,
               editrolefrom: {},
            // 修改表单的验证规则对象
            editroleFormrules: {
                email: [
                     { required: true, message: '请输入邮箱', trigger: 'blur' },
                ],
                mobile: [
                     { required: true, message: '请输入手机号', trigger: 'blur' },
                ]
            },
            // 角色id
            roleid:''
        }
    },
    created() {
        this.getrolelist()
    },
    methods: {
        async getrolelist() {
            const { data: res } = await this.$http.get('roles')
            // console.log(res)
            console.log(res)
           if (res.meta.status !== 200) {
                return this.$message.error('获取角色列表失败')
            }
            this.rolelist = res.data
            console.log(res.data)
        },
        async removeRightById(role, rightid) {
            const confirmresult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
              type: 'warning'
        }).catch(err => err)
        if (confirmresult !== 'confirm') {
          return this.$message.info('取消删除')
        }
        const { data:res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
         if (res.meta.status !== 200) {
                return this.$message.error('删除权限失败')
            }
            this.$message.success('删除权限成功')
            role.children = res.data
        },
        // 展示分配权限得对话框
        async showserrightdialog(role) {
          this.roleid = role.id
          const { data:res } = await this.$http.get('rights/tree')
          if (res.meta.status !== 200) {
                return this.$message.error('获取权限失败')
            } 
          this.rightlist = res.data       
          this.setrightdialogVisible = true
          this.getlistkey(role, this.defkey)
          console.log(this.rightlist)
        },
        // 通过递归的形式，获取角色下所有的三级权限的id，并保存到数组defkeys中
        getlistkey(node, arr) {
          // 若当前的node节点不包含children属性说明该节点是三级节点
          if (!node.children) {
            return arr.push(node.id)
          }
          node.children.forEach(item => 
          this.getlistkey(item, arr))
        },
        // 监听关闭对话框事件
        setrightdialogclose() {
          this.defkey = []
        },
        // 添加角色
         addrole() {
            this.$refs.roleFormref.validate(async valid => {
                if (!valid) return
                // 可以发起对添加用户的网络请求
                const { data: res } = await this.$http.post('roles', this.roleForm)
                if (res.meta.status !== 201) {
                    this.$message.error('角色添加失败')
                }
                // 隐藏对话框
                this.adddialogVisible = false
                // 重新获得用户列表数据
                console.log(this.roleForm)
                console.log(123546)
                console.log(res)
                this.getrolelist()              
            })
        },
        // 编辑角色
        async showeditroledialog(id) {
            this.editroledialogVisible = true
            const { data:res } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) {
                    this.$message.error('查询角色信息失败')
                }
            this.$message.success('查询角色信息成功')
            this.editrolefrom = res.data
            console.log(123546)
            console.log(res)    
        },
        // 监听修改用户对话框的关闭事件
         editroledialogclose() {
            this.$refs.editFormref.resetFields()
         },
        // 修改用户信息并提交
         editroleinfo() {
            this.$refs.editFormref.validate(async valid => {
                // console.log(valid)
                if (!valid) return
                const { data:res } = await this.$http.put('roles/' + this.editrolefrom.roleId,
                { roleName: this.editrolefrom.roleName,
                roleDesc: this.editrolefrom.roleDesc })
                if (res.meta.status !== 200) {
                    this.$message.error('更新用户信息失败')
                }
            // 关闭对话框
            console.log(this.editrolefrom)
            console.log(res)
            this.editroledialogVisible = false
            // 刷新数据列表
            this.getrolelist()
            // 提示成功
            this.$message.success('查询用户信息成功') 
            })           
         },
         // 根据用户id删除信息
         async removerolebyid(id) {
         // 提示用户是否删除
         const ress = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((error) => {
          return error         
        });
        // 如果用户确定删除，返回值为字符串confirm
        if (ress !== 'confirm') {
          this.$message.info('已经取消删除')
        }
        const { data:res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) {
            return this.$message.error('删除用户信息失败')
         }
         this.getrolelist()
         this.$message.success('删除用户信息成功')       
    },
    // 为角色分配权限
    async allrights() {
      console.log(123456)
      const keys = [
       ...this.$refs.treeref.getCheckedKeys(),
       ...this.$refs.treeref.getHalfCheckedKeys()  
      ]     
       const idstr = keys.join(',')
       console.log(idstr)
       const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, { rids: idstr })
       if (res.meta.status !== 200) {
            return this.$message.error('分配权限失败')
         }
         // console.log(res)
         this.getrolelist()
         this.setrightdialogVisible = false 
    }
    }
}
</script>
<style scoped lang="less">
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: solid 1px;
}
.bdbotton{
    border-bottom: solid 1px;
    color: #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
